package com.zxm.sunshineaiary.activity;

import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.zxm.sunshineaiary.activity.base.MybaseActivity;
import com.zxm.sunshineaiary.info.DateInfo;
import com.zxm.sunshineaiary.info.DiaryInfo;
import com.zxm.sunshineaiary.sql.service.SqlService;
import com.zxm.sunshineaiary.util.CharsUtil;
import com.zxm.sunshineaiary.util.StorageFile;
import com.zxm.sunshineaiary.view.mydialog.WeatherDialog;
import com.zxm.sunshineaiary.view.myedittext.FingerPaint;
import com.zxm.sunshineaiary.view.myedittext.MyEditText;
import com.zxm.sunshineaiary.view.myedittext.PaintColorLayout;

public class DiaryActivity extends MybaseActivity implements OnClickListener,
		OnTouchListener, PaintColorLayout.OnPaintColorListener {

	private final String TAG = "DiaryActivity";
	private final String FILE_TEXT_NAME = "DATE";
	private final int PING = 5;

	private FingerPaint mFingerPaint = null;
	private MyEditText mEditText = null;
	private PaintColorLayout mPaintColorLayout = null;
	private StorageFile mStorageFile = StorageFile.getInsance();
	private SqlService mSqlService = null;
	private DateInfo mDateIndo = DateInfo.getInstance();
	private DiaryInfo mDiaryInfo = null;
	private WeatherDialog mWeatherDialog = null;

	private TextView mTextDay = null;
	private View drawPop = null;
	private PopupWindow mPop = null;
	private Bitmap mBitmap = null;
	private ImageView mDrawPopOpenButton = null;
	private ImageView mBackButton = null;
	private ImageView mSaveButton = null;
	private ImageView mWeatherButton = null;

	private int imageName = 0;
	private final int POPUPHEIGHT = 400;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diary);
		mSqlService = SqlService.getInstance(this);
		findView();
		setListener();
		createPopUpWindow();
	}

	@Override
	protected void onResume() {
		setTextView(mTextDay);
		// 阻止键盘自动弹出
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
		getDiarySql();
		getDiaryOfEditText();
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();

	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.drawPopImage:
			upPopupWindow();
			break;
		case R.id.popupwindow_closebutton:
			mPop.dismiss();
			mDrawPopOpenButton.setVisibility(View.VISIBLE);
			break;
		case R.id.diary_brakButton:
			startNextActivity(DateMenuActivity.class);
			break;
		case R.id.diary_saveButton:
			mEditText.clearFocus();
			saveEditText();
			break;
		case R.id.diary_weatherView:
			new WeatherDialog(this).show();
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		try {
			if (event.getAction() == event.ACTION_UP && v == drawPop) {
				boolean popState = drawImageOnEditText(mFingerPaint);
				if (!popState) {
					closePopUpWindow();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	private void findView() {
		mTextDay = (TextView) findViewById(R.id.diary_text_day);
		mEditText = (MyEditText) findViewById(R.id.myEditText);
		mDrawPopOpenButton = (ImageView) this.findViewById(R.id.drawPopImage);
		mPaintColorLayout = (PaintColorLayout) this
				.findViewById(R.id.diary_paintColorLayou);
		mBackButton = (ImageView) findViewById(R.id.diary_brakButton);
		mSaveButton = (ImageView) findViewById(R.id.diary_saveButton);
		mWeatherButton = (ImageView) findViewById(R.id.diary_weatherView);
	}

	private void setListener() {
		mDrawPopOpenButton.setOnClickListener(this);
		mBackButton.setOnClickListener(this);
		mPaintColorLayout.setOnPaintColorListener(this);
		mSaveButton.setOnClickListener(this);
		mWeatherButton.setOnClickListener(this);
	}

	private void setTextView(TextView textView) {
		Log.v(TAG, mDateIndo.day);
		textView.setText(mDateIndo.day);
	}

	/**
	 * 根据用用户保存的文本信息，替换出图片
	 * 
	 * @param str
	 *            用户文本信息
	 */
	private void appendImage(CharSequence str) {
		try {
			mEditText.setText(str);
			Spannable ss = mEditText.getText();
			mEditText.setText(CharsUtil.getImageName(mDateIndo, ss, str));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 生成popUpWindow对象
	 */
	private void createPopUpWindow() {
		LayoutInflater mLayoutInflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		drawPop = mLayoutInflater.inflate(R.layout.popupwindow, null);
		drawPop.setOnTouchListener(this);
		mPop = new PopupWindow(drawPop, LayoutParams.FILL_PARENT,
				CharsUtil.dipTopx(this, POPUPHEIGHT));
		mPop.setAnimationStyle(android.R.style.Animation_InputMethod);

		mFingerPaint = (FingerPaint) drawPop.findViewById(R.id.finger_paint);
		ImageView closeButton = (ImageView) drawPop
				.findViewById(R.id.popupwindow_closebutton);
		closeButton.setOnClickListener(this);
	}

	private void upPopupWindow() {
		mDrawPopOpenButton.setVisibility(View.INVISIBLE);
		mPaintColorLayout.showLayout();
		mPop.showAtLocation(findViewById(R.id.drawPopImage), Gravity.BOTTOM, 0,
				0);
	}

	private void closePopUpWindow() {
		mDrawPopOpenButton.setVisibility(View.VISIBLE);
		mPaintColorLayout.closeLayout();
		mPop.dismiss();
	}

	/**
	 * 从数据库获得数据
	 */
	private void getDiarySql() {
		mDiaryInfo = mSqlService.getDiary(mDateIndo.getDate());
		if (null != mDiaryInfo) {
			imageName = mDiaryInfo.getImageName();
		}
	}

	/**
	 * 把用户存储到SD卡上的图片增加到用户EditText文本中，生成"[*]" 标记
	 * 
	 * @param imageName
	 */
	private void addImageOnText() {

		int start = mEditText.getSelectionStart();
		String imagePath = mStorageFile.getFilePath(mDateIndo, imageName + "",
				mStorageFile.PNG);

		StringBuffer strBuf = new StringBuffer();
		strBuf.append("[");
		strBuf.append(imageName);
		strBuf.append("]");

		Spannable ss = mEditText.getText().insert(start, strBuf.toString());
		Drawable d = Drawable.createFromPath(imagePath);
		int drawableH = d.getMinimumHeight();
		int drawableW = d.getMinimumWidth();

		d.setBounds(0, 0, drawableW, drawableH);
		ImageSpan span = new ImageSpan(d, imageName + ".png",
				ImageSpan.ALIGN_BASELINE);
		ss.setSpan(span, start, start + strBuf.toString().length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	}

	/**
	 * 如果用户输入不为空就把用户日记信息存储到SD中和数据库中
	 */
	private void saveEditText() {
		if (isEidtNull()) {
			String text = mEditText.getText().toString();
			try {
				mStorageFile.saveText(mDateIndo, FILE_TEXT_NAME, text);
				mSqlService.saveDiary(mDateIndo.getDate(), new DiaryInfo(
						imageName + "", null, null));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private boolean isEidtNull() {
		if (mEditText.getText().toString().equals("")) {
			return false;
		}
		return true;
	}

	/**
	 * 把图片存入SD并显示到EditText,如果用户有图画返回true,没有返回false
	 * 
	 * @param mFingerPaint
	 * @throws IOException
	 */
	private boolean drawImageOnEditText(FingerPaint mFingerPaint)
			throws IOException {
		mBitmap = mFingerPaint.getBitmap();
		if (null != mBitmap) {
			String name = getImageName();
			Log.v(TAG, "name===" + name);
			mStorageFile.saveBitmapOfSd(mDateIndo, mBitmap, name);
			addImageOnText();
			mFingerPaint.clearCanvas();
			return true;
		}
		return false;
	}

	/**
	 * 读取日记的历史记录
	 * 
	 * @throws IOException
	 */
	private void getDiaryOfEditText() {
		Log.v(TAG, "getDiaryOfEditText===" + mDateIndo.getYear());
		Log.v(TAG, "getDiaryOfEditText===" + mDateIndo.month);
		Log.v(TAG, "getDiaryOfEditText===" + mDateIndo.day);

		CharSequence text = mStorageFile.getStringOfSD(mDateIndo,
				FILE_TEXT_NAME);
		if (null != text) {
			appendImage(text);
		}
	}

	private String getImageName() {
		imageName += 1;
		return imageName + "";
	}

	@Override
	public void paintColor(int color) {
		mFingerPaint.setDrawLineColor(color);
	}
}
